
/********************************************************************/
/* Copyright (C) SSE-USTC, 2010                                     */
/*                                                                  */
/*  FILE NAME             :  parser.c                               */
/*  PRINCIPAL AUTHOR      :  Mengning                               */
/*  SUBSYSTEM NAME        :  ChatSys                                */
/*  MODULE NAME           :  ChatSys                                */
/*  LANGUAGE              :  C                                      */
/*  TARGET ENVIRONMENT    :  ANY                                    */
/*  DATE OF FIRST RELEASE :  2010/11/26                             */
/*  DESCRIPTION           :  implement of ChatSys PDU parser        */
/********************************************************************/

/*
 * Revision log:
 *
 * Created by Mengning,2010/11/26
 *
 */
 
#include<string.h> 			/* memcpy 		*/
#include "socketwrapper.h" 	/* Ntohs/Htons 	*/ 
#include "parser.h" 	

typedef struct ChatSysPdu
{
	char 	Version:4;
	char 	MsgType:4;
	char	SerialNumber;
	short 	MsgLen;
	char	Msg[MAX_NUM_STR];	
}tChatSysPdu;

/*
 * Parse the ChatSys PDU to ChatSys Msg
 * input	: char * pdu , Memory allocate outside
 * output	: tChatSysMsg *Msg , Memory allocate outside
 * return	: SUCCESS(0)/FAILURE(-1)
 *
 */
int ChatSysPduParser(char * pdu,tChatSysMsg *Msg)
{
	if(pdu == NULL || Msg == NULL)
	{
		return FAILURE;
	}
	tChatSysPdu *pInputChatSysPdu = (tChatSysPdu *)pdu;
	tChatSysMsg *pRequestMsg =  Msg;
	pRequestMsg->Version = pInputChatSysPdu->Version;
	pRequestMsg->MsgType = pInputChatSysPdu->MsgType;
	pRequestMsg->SerialNumber = pInputChatSysPdu->SerialNumber;
	pRequestMsg->MsgLen = Ntohs(pInputChatSysPdu->MsgLen);
	memcpy(pRequestMsg->Msg,pInputChatSysPdu->Msg,pRequestMsg->MsgLen);
	pRequestMsg->Msg[pRequestMsg->MsgLen] = '\0';
	return SUCCESS;
}
/*
 * Format the ChatSys Msg to ChatSys PDU
 * input	: char * pdu , Memory allocate outside
 * output	: tChatSysMsg *Msg , Memory allocate outside
 * return	: SUCCESS(0)/FAILURE(-1)
 *
 */
int ChatSysPduFormat(char * pdu,tChatSysMsg *Msg)
{
	if(pdu == NULL || Msg == NULL)
	{
		return FAILURE;
	}
	tChatSysPdu *pOutputChatSysPdu = (tChatSysPdu *)pdu;
	tChatSysMsg *pResponseMsg = Msg;
	pOutputChatSysPdu->Version = pResponseMsg->Version;
	pOutputChatSysPdu->MsgType = pResponseMsg->MsgType;
	pOutputChatSysPdu->SerialNumber = pResponseMsg->SerialNumber;
	pOutputChatSysPdu->MsgLen = Htons(pResponseMsg->MsgLen);
	memcpy(pOutputChatSysPdu->Msg,pResponseMsg->Msg,pResponseMsg->MsgLen);
	pOutputChatSysPdu->Msg[pResponseMsg->MsgLen] = '\0';
	return SUCCESS;	
}
